import { MessagePlugin } from 'tdesign-vue-next';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { setAuthorization, getHeardToken, getHeardXtoken, setMd5Info, removeAuthorization } from './api/utils';
import { getPermissionStore, getUserStore } from '@/store';
import router from '@/router';
import { outLogin } from '@/utils/minxin';

NProgress.configure({ showSpinner: false });

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const permissionStore = getPermissionStore();
  const { whiteListRouters } = permissionStore;

  const token = getHeardToken();
  if (to.path === '/login') {
    next();
    return;
  }
  if (token) {
    next();

    // const { roles } = userStore;
    // if (roles && roles.length > 0) {
    //   next();
    // } else {
    //   try {
    //     await userStore.getUserInfo();
    //     const { roles } = userStore;
    //     await permissionStore.initRoutes(roles);
    //     if (router.hasRoute(to.name)) {
    //       next();
    //     } else {
    //       next(`/`);
    //     }
    //   } catch (error) {
    //     MessagePlugin.error(error);
    //     next({
    //       path: '/login',
    //       query: { redirect: encodeURIComponent(to.fullPath) },
    //     });
    //     NProgress.done();
    //   }
    // }
  } else {
    next();
    // let url = window.location.href;
    // let redirectUrl = 'http://wz.wuzhan.art/#/login?redirect=' + url;
    // outLogin(redirectUrl);
    /* white list router */
    // if (whiteListRouters.indexOf(to.path) !== -1) {
    // next();
    // } else {
    //   next({
    //     path: '/login',
    //     query: { redirect: encodeURIComponent(to.fullPath) },
    //   });
    // }
    // NProgress.done();
  }
});

router.afterEach((to) => {
  if (to.path === '/login') {
    const userStore = getUserStore();
    const permissionStore = getPermissionStore();

    userStore.logout();
    permissionStore.restore();
  }
  NProgress.done();
});
